"""
Case Type   : GSC功能模块
Case Name   : gs_gsc_table_detail，指定库参数查看缓存信息
Create At   : 2022/04/25
Owner       : opentestcase024
Description :
    1、打开gsc开关;
    2、重启数据库生效;
    3、创建数据库;
    4、创建表并查询;
    5、查询所有库并进行连接;
    6、查询指定库不存在;
    7、查看指定库的缓存信息;
    8、三种参数查询所有库;
Expect      :
    1、打开gsc开关; 修改成功
    2、重启数据库生效; 重启成功
    3、创建数据库; 创建成功
    4、创建表并查询; 操作成功
    5、查询所有库并进行连接; 连接成功
    6、查询指定库不存在; 查询失败
    7、查看指定库的缓存信息; 查询结果包含指定数据库及共享库两个
    8、三种参数查询所有库; 查询所有库数量正确，且三种方式大于等于前一次查询结果
History     :
    Modified by peilinqian at 2025/1/21:teardown增加集群主备恢复动作，以防对其他用例产生影响
    modified：2022-8-30 by opentestcase024;增加一次查询，新增日志打印，查询缓存具体信息，方便定位缓存不一致问题；
    modified：2023-4-21 by opentestcase024;校验三种查询所有库方式时间不同导致后台会进行一些缓存，
        优化为只保证后一次结果大于等于前一次结果即可；
"""
import os
import time
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node


class GscTestCase(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)}:start----')
        self.log.info("----this is setup----")
        self.db_name = 'db_gsc0042'
        self.tb_name = 'tb_gsc0042'
        self.com = Common()
        self.constant = Constant()
        self.sh = CommonSH('PrimaryDbUser')
        self.pri_dbuser = Node(node='PrimaryDbUser')
        self.err_flag = "ERROR:  dbOid doesn't exist."

        step_txt = '----step0:查看数据库状态是否正常;----'
        self.log.info(step_txt)
        status_result = self.sh.get_db_cluster_status('status')
        self.assertTrue(status_result, '执行失败:' + step_txt)
        step_txt = '----step0:查看enable_global_syscache初始配置值;----'
        self.log.info(step_txt)
        self.init_para1 = self.com.show_param("enable_global_syscache")

    def test_main(self):
        if self.init_para1 == 'off':
            step_txt = '----step1:打开gsc开关; expect:修改成功----'
            self.log.info(step_txt)
            result = self.sh.execute_gsguc('set',
                                           self.constant.GSGUC_SUCCESS_MSG,
                                           f"enable_global_syscache= on")
            self.assertTrue(result, '执行失败:' + step_txt)

            step_txt = '----step2:重启数据库生效; expect:重启成功----'
            self.log.info(step_txt)
            restart = self.sh.restart_db_cluster()
            self.assertTrue(restart, '执行失败:' + step_txt)
            self.is_reset_para = True
        else:
            step_txt = '----gsc开关设置正常，跳过step1、step2----'
            self.log.info(step_txt)
            self.is_reset_para = False

        step_txt = f'----step3:创建数据库; expect:创建成功----'
        self.log.info(step_txt)
        create_db = f'drop database if exists {self.db_name};' \
            f'create database {self.db_name};'
        create_result = self.sh.execut_db_sql(create_db)
        self.log.info(create_result)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, create_result,
                      '执行失败:' + step_txt)

        step_txt = '----step4:创建表并查询; expect:操作成功----'
        self.log.info(step_txt)
        create_tb_sql = f"create table {self.tb_name} " \
            f"(c_integer integer,c_tinyint tinyint," \
            f"c_smallint smallint,c_binary_integer binary_integer," \
            f"c_bigint bigint,c_numeric numeric(10,4)," \
            f"c_number number(10,4),c_smallserial smallserial);" \
            f"select * from {self.tb_name};"
        create_result = self.sh.execut_db_sql(create_tb_sql,
                                              dbname=f'{self.db_name}')
        self.log.info(create_result)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, create_result,
                      '执行失败:' + step_txt)
        self.assertIn('0 rows', create_result, '执行失败:' + step_txt)

        time.sleep(2)

        step_txt = '----step5:查询所有库并进行连接; expect:连接成功----'
        self.log.info(step_txt)
        select_db_sql = "select datname from pg_database where datname " \
                        "not like('template%');"
        select_db_result = self.sh.execut_db_sql(select_db_sql)
        self.log.info(select_db_result)
        db_list = select_db_result.splitlines()[2:-1:1]
        for i in db_list:
            con_result = self.sh.execut_db_sql('select current_database();',
                                               dbname=f'{i}')
            self.log.info(con_result)
            self.assertIn(i, con_result, '执行失败:' + step_txt)

        self.log.info('缓存所有库数量为：所有库+0库')
        self.total_db_num = len(db_list) + 1

        step_txt = '----step6:查询指定库不存在; expect:查询失败----'
        self.log.info(step_txt)
        check_sql1 = f"select count(*) from " \
            f"gs_gsc_table_detail(123123);"
        select_result = self.sh.execut_db_sql(check_sql1)
        self.log.info(select_result)
        self.assertIn(self.err_flag, select_result, '执行失败:' + step_txt)

        step_txt = '----step7:查看指定库的缓存信息; expect:查询结果包含指定数据库及共享库两个----'
        self.log.info(step_txt)
        db_oid_sql = f"select oid from pg_database where " \
            f"datname = '{self.db_name}';"
        db_oid = self.sh.execut_db_sql(db_oid_sql).splitlines()[-2].strip()
        self.log.info("指定数据库oid：" + db_oid)
        check_result7 = self.check_db_gsc(db_oid)
        self.assertEqual(len(check_result7[0]), 2, '执行失败:' + step_txt)

        step_txt = '----step8:三种参数查询所有库; expect:查询所有库数量正确，' \
                   '且三种方式大于等于前一次查询结果----'
        self.log.info(step_txt)
        check_sql = f"select * from gs_gsc_table_detail(null);"
        select_result = self.sh.execut_db_sql(check_sql)
        self.log.info(select_result)
        check_sql = f"select * from gs_gsc_table_detail(-1);"
        select_result = self.sh.execut_db_sql(check_sql)
        self.log.info(select_result)
        check_sql = f"select * from gs_gsc_table_detail();"
        select_result = self.sh.execut_db_sql(check_sql)
        self.log.info(select_result)
        check_result8_1 = self.check_db_gsc("null")
        check_result8_2 = self.check_db_gsc("-1")
        check_result8_3 = self.check_db_gsc("")
        self.assertGreaterEqual(len(check_result8_1[0]),
                                self.total_db_num,
                                '执行失败:' + step_txt)
        self.assertGreaterEqual(len(check_result8_2[0]),
                                len(check_result8_1[0]),
                                '执行失败:' + step_txt)
        self.assertGreaterEqual(len(check_result8_3[0]),
                                len(check_result8_2[0]),
                                '执行失败:' + step_txt)

    def check_db_gsc(self, db_oid):
        """
        :param: db_oid: 查询数据库oid
        :return: 返回数据库与对应查询结果字典
        """
        check_sql = f"select database_oid,count(*) from " \
            f"gs_gsc_table_detail({db_oid}) group by database_oid " \
            f"order by database_oid;"
        select_result = self.sh.execut_db_sql(check_sql)
        self.log.info(select_result)
        result = select_result.splitlines()[2:-1]
        db_list = []
        db_dict = dict()
        for i in result:
            key_name = i.split('|')[0].strip()
            key_value = int(i.split('|')[1].strip())
            db_dict[key_name] = key_value
            db_list.append(key_name)
        self.log.info(db_list)
        self.log.info(db_dict)
        return db_list, db_dict

    def tearDown(self):
        step_txt = '----this is teardown----'
        self.log.info(step_txt)
        step1_txt = '----清理数据库; expect:清理成功----'
        self.log.info(step1_txt)
        drop_cmd = f"drop database if exists {self.db_name};"
        drop_result = self.sh.execut_db_sql(drop_cmd)
        self.log.info(drop_result)

        if self.is_reset_para:
            self.step2_txt = '----恢复参数为初始值并查询; expect:设置成功----'
            self.log.info(self.step2_txt)
            self.msg1 = self.sh.execute_gsguc('set',
                                              self.constant.GSGUC_SUCCESS_MSG,
                                              f"enable_global_syscache "
                                              f"={self.init_para1}")

            self.step3_txt = '----重启数据库生效; expect:重启成功----'
            self.log.info(self.step3_txt)
            self.restart = self.sh.restart_db_cluster()
            self.step4_txt = '----查询数据库状态; expect:状态正常----'
            self.log.info(self.step4_txt)
            status = self.sh.exec_cm_ctl(mode='query', param='-Cv')
            self.log.info(status)
            p_status = status.splitlines()[-1].split('|')[0].split('6001')[-1]
            if 'Primary' in p_status and "cluster_state   : Normal" in status:
                self.log.info('---集群状态正常，无需恢复为初始状态---')
            else:
                recovery = self.sh.exec_cm_ctl(mode='switchover',
                                                   param='-a')
                self.log.info(recovery)
                time.sleep(10)
            self.status_result = self.sh.get_db_cluster_status('status')

        self.log.info(f'----{os.path.basename(__file__)}:end----')
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_result,
                      "执行失败" + step_txt + step1_txt)
        if self.is_reset_para:
            self.assertTrue(self.msg1, '执行失败:' + self.step2_txt)
            self.assertTrue(self.restart, '执行失败:' + self.step3_txt)
            self.assertTrue(self.status_result, '执行失败:' + self.step4_txt)
